package com.tssup.fesco.init;

import com.tssup.fesco.common.cache.Cache;
import com.tssup.fesco.common.cache.redis.RedisKeyConstants;
import com.tssup.fesco.common.exeception.CacheException;
import com.tssup.fesco.common.exeception.ParameterException;
import com.tssup.fesco.common.exeception.RetException;
import com.tssup.fesco.sales.rule.persistent.mapper.RRegionMapper;
import com.tssup.fesco.sales.rule.persistent.pojo.RRegion;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHander;
import com.xxl.job.core.log.XxlJobLogger;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;


/**
 * 缓存数据-全部Region
 * @author haomin
 * @date 2017/6/20
 */
@JobHander(value="CacheRegionDataJob")
@Service
public class CacheRegionDataJob extends IJobHandler{

    @Autowired
    private Cache cache;

    @Autowired
    private RRegionMapper regionMapper;

    @Override
    public ReturnT<String> execute(String... strings) throws Exception {
        try {
            XxlJobLogger.log("缓存数据-全部Region");
            List<RRegion> regions = regionMapper.selectAllRegion();
            regions.stream().forEach(rRegion -> {
                if (rRegion != null && rRegion.getRegionId() != null) {
                    try {
                        cache.set(RedisKeyConstants.getRegionKey(rRegion.getRegionId()), rRegion);
                        XxlJobLogger.log("缓存数据Region:"+rRegion.getRegionId());
                    } catch ( CacheException e ) {
                        XxlJobLogger.log("缓存数据Region失败，id:"+rRegion.getRegionId());
                    }
                }
            });
            XxlJobLogger.log("缓存数据-全部Region");
        }catch (RetException re){
            return new ReturnT<String>(Integer.parseInt(re.getRetCode()), re.getResMsg());
        } catch (ParameterException pe) {
            return new ReturnT<String>(Integer.parseInt(pe.getCode()), pe.getMessage());
        } catch (Exception e){
            return new ReturnT<String>(500,e.getMessage());
        }
        return ReturnT.SUCCESS;
    }
}
